package controller

import (
	"hytx_manager/models"
	"hytx_manager/pkg/setting"
	"strconv"
	"time"

	"github.com/astaxie/beego/validation"

	"github.com/Unknwon/com"

	"github.com/gin-gonic/gin"
)

func EnterpriseList(c *gin.Context) {
	identStatus := c.Query("is_ident")
	status := c.Query("status")
	staffName := c.Query("name")
	staffPhone := c.Query("phone")
	comName := c.Query("com_name")
	beginTime := c.Query("begin_time")

	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	limit, _ := strconv.Atoi(c.DefaultQuery("limit", strconv.Itoa(setting.AppSetting.PageSize)))

	data, paginate := models.GetEnterpriseList(page, limit, identStatus, status, staffName, staffPhone, comName, beginTime)

	render(c, gin.H{
		"paginate": paginate,
		"data":     data,
	})
}

func GetStaffList(c *gin.Context) {
	enterpriseId := com.StrTo(c.Param("enterprise_id")).MustInt()
	staffName := c.Query("name")
	staffPhone := c.Query("phone")
	beginTime := c.Query("begin_time")

	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	limit, _ := strconv.Atoi(c.DefaultQuery("limit", strconv.Itoa(setting.AppSetting.PageSize)))

	data, paginate := models.GetStaffList(page, limit, enterpriseId, staffName, staffPhone, beginTime)

	render(c, gin.H{
		"paginate": paginate,
		"data":     data,
	})
}

func DisableAccount(c *gin.Context) {
	uid := com.StrTo(c.Param("uid")).MustInt()
	status := com.StrTo(c.PostForm("status")).MustInt()
	err := models.DB.Exec("UPDATE enterprise_users SET `status` = ? WHERE `id` = ?", status, uid).Error
	if err != nil {
		fail(c, err.Error())
		return
	}
	success(c)
}

func IdentList(c *gin.Context) {
	identStatus := c.Query("is_ident")
	status := c.Query("status")
	staffName := c.Query("name")
	staffPhone := c.Query("phone")
	comName := c.Query("com_name")
	beginTime := c.Query("begin_time")

	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	limit, _ := strconv.Atoi(c.DefaultQuery("limit", strconv.Itoa(setting.AppSetting.PageSize)))

	data, paginate := models.GetIdentList(page, limit, identStatus, status, staffName, staffPhone, comName, beginTime)

	render(c, gin.H{
		"paginate": paginate,
		"data":     data,
	})
}

func EnterInfo(c *gin.Context) {
	id := com.StrTo(c.Param("id")).MustInt()
	var res struct {
		Id        int    `json:"id"`
		Logo      string `json:"logo"`
		ComName   string `json:"com_name"`
		Address   string `json:"address"`
		AreaName  string `json:"area_name"`
		IdentData string `json:"ident_data"`
		Name      string `json:"name"`
		Avatar    string `json:"avatar"`
		Job       string `json:"job"`
	}
	err := models.DB.Table("enterprise e").Joins("left join enterprise_staff es on e.id = es.enterprise_id ").
		Select("e.id,e.logo,e.name as com_name,e.address,e.area_name,e.ident_data,es.name,es.avatar,es.job").
		Where("es.user_id = ?", 0).Where("e.id = ?", id).Scan(&res).Error
	if err != nil {
		fail(c, err.Error())
		return
	}
	render(c, res)
}

func Ident(c *gin.Context) {
	id := com.StrTo(c.Param("id")).MustInt()
	isIdent := com.StrTo(c.PostForm("is_ident")).MustInt()
	msg := c.PostForm("msg")
	if isIdent == 2 && len(msg) == 0 {
		msg = "恭喜，企业认证成功！"
	}
	tx := models.DB.Begin()
	r1 := tx.Exec("UPDATE enterprise SET `is_ident` = ? WHERE `id` = ?", isIdent, id)
	r2 := tx.Exec("INSERT INTO message(`to`,`title`,`content`,`target_type`,`created_at`) VALUES (?,?,?,?,?) ", id, "企业认证结果", msg, "enterprise", time.Now())
	if r1.Error != nil || r2.Error != nil {
		tx.Rollback()
		fail(c, "数据库操作失败")
		return
	}
	tx.Commit()
	success(c)
}

func StaffRecharges(c *gin.Context) {
	length := c.DefaultQuery("length", "")
	comName := c.DefaultQuery("name", "")
	staffPhone := c.DefaultQuery("phone", "")
	beginTime := c.DefaultQuery("begin_time", "")

	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	limit, _ := strconv.Atoi(c.DefaultQuery("limit", strconv.Itoa(setting.AppSetting.PageSize)))

	data, paginate := models.StaffRechargesList(page, limit, length, comName, staffPhone, beginTime)

	render(c, gin.H{
		"paginate": paginate,
		"data":     data,
	})
}

func EnterpriseSelfList(c *gin.Context) {
	phone := c.Query("phone")
	// 查询users表 type
	users := models.Users{
		Phone: phone,
	}
	user, _ := users.GetUserInfoByPhone()
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	limit, _ := strconv.Atoi(c.DefaultQuery("limit", strconv.Itoa(setting.AppSetting.PageSize)))

	if user.Type == 1 {
		enterprise := models.Enterprise{
			PlacePartnerId: user.ID,
		}

		data, paginate := enterprise.GetPlacePartnerIdList(page, limit)

		render(c, gin.H{
			"paginate": paginate,
			"data":     data,
		})
	}
	if user.Type == 2 {
		enterprise := models.Enterprise{
			OperatorId: user.ID,
		}

		data, paginate := enterprise.GetOperatorIdList(page, limit)

		render(c, gin.H{
			"paginate": paginate,
			"data":     data,
		})
	}
	if user.Type == 3 {
		enterprise := models.Enterprise{
			SalesmanId: user.ID,
		}

		data, paginate := enterprise.GetSalesmanIdList(page, limit)

		render(c, gin.H{
			"paginate": paginate,
			"data":     data,
		})
	}

}

func StaffCount(c *gin.Context) {
	id, _ := strconv.Atoi(c.Query("id"))

	s := models.EnterpriseStaff{
		EnterpriseId: id,
	}
	render(c, gin.H{
		"count": s.Count(),
	})
}

func UserCount(c *gin.Context) {
	id, _ := strconv.Atoi(c.Query("id"))

	s := models.Users{
		EnterpriseUserId: id,
	}
	render(c, gin.H{
		"count": s.Count(),
	})
}
func EnterpriseRecharges(c *gin.Context) {
	status := c.DefaultQuery("status", "")
	comName := c.DefaultQuery("name", "")
	phone := c.DefaultQuery("phone", "")
	beginTime := c.DefaultQuery("begin_time", "")

	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	limit, _ := strconv.Atoi(c.DefaultQuery("limit", strconv.Itoa(setting.AppSetting.PageSize)))

	data, paginate := models.EnterpriseRechargesList(page, limit, comName, phone, beginTime, status)

	render(c, gin.H{
		"paginate": paginate,
		"data":     data,
	})
}

func EnterpriseVip(c *gin.Context) {
	id := com.StrTo(c.DefaultPostForm("enterprise_id", "0")).MustInt()
	createAt := c.DefaultPostForm("create_at", time.Now().String())
	overedAt := c.DefaultPostForm("overed_at", "")

	valid := validation.Validation{}
	valid.Min(id, 1, "id").Message("enterprise_id大于0")
	valid.Required(overedAt, "overed_at").Message("到期时间不能为空")

	if valid.HasErrors() {
		fail(c, "参数不合法")
		return
	}
	tx := models.DB.Begin()

	t1 := tx.Exec("UPDATE enterprise SET `overed_at` = ? WHERE `id` = ?", overedAt, id)
	t2 := tx.Exec("INSERT INTO enterprise_recharges(`pay_type`,`is_pay`,`enterprise_id`,`overed_at`,`created_at`,`pay_time`,`vip_fee_config_comment`,`vip_fee_config_id`,`out_trade_no`)"+
		" VALUES (?,?,?,?,?,?,?,?,?)", "后台开通", 1, id, overedAt, createAt, createAt, "年度会员", 3, time.Now().Unix())

	if t1.Error != nil || t2.Error != nil {
		fail(c, "数据操作失败")
		tx.Rollback()
		return
	}
	tx.Commit()
	success(c)
}

func EnterResers(c *gin.Context) {
	status := c.DefaultQuery("status", "")
	comName := c.DefaultQuery("name", "")
	phone := c.DefaultQuery("phone", "")

	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	limit, _ := strconv.Atoi(c.DefaultQuery("limit", strconv.Itoa(setting.AppSetting.PageSize)))

	data, paginate := models.EnterResers(page, limit, comName, phone, status)

	render(c, gin.H{
		"paginate": paginate,
		"data":     data,
	})
}
